/*
 * @Description  : 
 * @Version      : 1.0
 * @Author       : Shiming
 * @Date         : 2022-03-01 15:13:03
 * @LastEditors  : Shiming
 * @LastEditTime : 2022-04-13 10:41:08
 * @FilePath     : \\tms-obc-web\\src\\app\\routes\\supply-management\\model\\import-supply\\import-supply.component.ts
 * Copyright (C) 2022 huzhenhong. All rights reserved.
 */
import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn } from '@delon/abc/st';
import { SFComponent, SFSchema, SFSchemaEnum, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { SupplyManagementService } from '../../services/supply-management.service';
import { apiConf } from '@conf/api.conf';

@Component({
  selector: 'app-supply-management-import-supply',
  templateUrl: './import-supply.component.html',
})
export class SupplyManagementImportSupplyComponent implements OnInit {
  record: any = {};
  files: any;
  fileName: any;
  status: boolean = true
  files2: any;
  schema: SFSchema = {};
  load = false
  ui: SFUISchema = {};
  networkTransporter: any; // 网络货运人id
  uploadUrl = apiConf.file_upload_url;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public service: SupplyManagementService
  ) { }

  ngOnInit(): void {
    this.initSF();
    console.log(this.record)
  }

  initSF() {
    this.schema = {
      properties: {
        shipperAppUserId: {
          title: '货主',
          type: 'string',
          maxLength: 30,
          ui: {
            widget: 'select',
            // serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            onSearch: (q: any) => {
              console.log(q === ' ')
              let str =q.replace(/^\s+|\s+$/g,"");
              if (str) {
                return this.service
                  .request(this.service.$api_enterpriceList, { enterpriseName: str })
                  .pipe(map(res => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.id } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
            change: (q: any) => {
              let str =q.replace(/^\s+|\s+$/g,"");
              if (str) {
                this.getRegionCode(str);
                this.getRegionCode2(str);
              }
            }
          } as SFSelectWidgetSchema
        },
        enterpriseInfoId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'text',
          },
          default: '确认货主后带出'
        },
        enterpriseProjectId: {
          type: 'string',
          title: '项目',
          ui: {
            widget: 'select',
            placeholder: '请选择'
          } as SFSelectWidgetSchema
        },
        fileName: {
          type: 'string',
          title: '导入货源信息',
          ui: {
            widget: 'custom'
          }
        },
        file: {
          type: 'string',
          title: '',
          ui: {
            widget: 'custom'
          }
        },
      },
      required: ['shipperAppUserId', 'enterpriseProjectId','enterpriseInfoId','fileName'],
    };
    this.ui = {
      '*': {
        grid: { span: 20 },
      },
      '$fileName': {
        spanLabelFixed: 130,
        grid: { span: 20 },
      },
      '$file': {
        spanLabelFixed: 130,
        grid: { span: 20 },
      },
    };
  }
  getRegionCode(regionCode: any) {
    console.log(regionCode);
    return this.service
      .request(this.service.$api_get_enterprise_project, { id: regionCode })
      .pipe(
        map(res =>
          res.map((item: any) => ({
            label: item.projectName,
            value: item.id
          }))
        )
      )
      .subscribe(res => {
        this.sf.getProperty('/enterpriseProjectId')!.schema.enum = res;
        this.sf.getProperty('/enterpriseProjectId')!.widget.reset(res);
      });
  }
  getRegionCode2(regionCode: any) {
    console.log(regionCode);
    return this.service
      .request(this.service.$api_getNetworkTransporter, { id: regionCode }).subscribe((res: any) => {
        console.log(res)
        this.networkTransporter = res.networkTransporter
        this.sf.getProperty('/enterpriseInfoId')!.widget.reset(res?.netTranName);
        this.sf.setValue('/enterpriseInfoId', res?.netTranName)
      });
  }
  save(): void {
    if(!this.sf?.value?.shipperAppUserId || !this?.networkTransporter || !this.sf?.value?.enterpriseProjectId || !this.sf?.value?.fileName) {
      this.service.msgSrv.error('请填写必填项并上传文件！')
      return
    }
    this.load =true;
    const formData : any= new FormData();
    this.files?.forEach((file: any) => {
      formData.append('file', file);
      formData.append('shipperAppUserId', this.sf?.value?.shipperAppUserId);
      formData.append('enterpriseInfoId', this?.networkTransporter);
      formData.append('enterpriseProjectId', this.sf?.value?.enterpriseProjectId);
    });
  
    console.log(formData)
    this.service.request(this.service.$api_goodsResourceOperateImport, formData).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('导入成功');
       this.load =false;
        this.modal.destroy({ ...res });
      }
    });
  }

  close(): void {
    this.modal.destroy();
  }
  handleChange(info: NzUploadChangeParam): void {
    switch (info?.file?.status) {
      case 'uploading':
        break;
      case 'done':
        console.log(info);
        let file = info?.file;
        let fileName = file?.response.name;
        this.sf?.setValue('/fileName', fileName);
        this.sf?.setValue('/file', file?.response?.url);
        break;
      case 'error':
        this.service.msgSrv.error('出错误了');
        break;
    }
  }
  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    let fileName = file?.name;
    this.files = [];
    this.files.push(file);
    this.sf?.setValue('/fileName', fileName);
    return false;
  };
  downFile() {
   this.service.downloadFile(this.service.$api_exportGoodsResourceOperateTemplate);
  }
  clearFile() {
    this.fileName = null;
    this.sf?.setValue('/fileName', null);
  }
}
